package file.day9_25.test;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    private Socket socket;
    public Client2(){
        System.out.println("正在连接服务器");

        try {
            socket = new Socket("localhost",8094);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("连接服务器成功");
    }

    private void start(){
        try (
                PrintWriter pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream(),"UTF-8"
                                )
                        ),true
                );
                ){


            ServerHandler serverHandler = new ServerHandler();
            Thread t = new Thread(serverHandler);
            t.start();

            Scanner scanner = new Scanner(System.in);

            while (true){
                System.out.println("请输入要发送的消息：");
                String message = scanner.nextLine();
                if(message.equals("exit"))break;
                pw.println(message);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ServerHandler implements Runnable{
        public void run(){
            try (
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(
                                    socket.getInputStream(),"UTF-8"
                            )
                    );
                    ){


                String message = null;
                while ((message = br.readLine()) != null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                System.out.println("与服务端断开");
            }
        }
    }

    public static void main(String[] args) {
        Client2 client = new Client2();
        client.start();
    }
}
